<?php
/**
 * Author: xx.com
 * Date: 2019年8月15日
 */
namespace Admin\Controller;
use Think\AjaxPage;

class FreeprizesController extends BaseController {
    /**----------------------------------------------*/
     /*                先到先得控制器                 */
    /**----------------------------------------------*/
    /*
     * 先到先得活动列表
     */
    public function index(){
        //获取列表
        
    	$count =  M('free_prizes')->count();
    	$Page = new \Think\Page($count,10);        
        $show = $Page->show();
        $lists = M('free_prizes')->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        $this->assign('lists',$lists);
        $this->assign('page',$show);// 赋值分页输出   
        $this->assign('freeprizess',C('FREEPRIZES_STATUS'));
        $this->display();
    }

    /*
     * 添加编辑一个活动
     */
    public function freeprizes_info(){
        if(IS_POST){
        	$data = I('post.');
            $data['start_time'] = strtotime($data['start_time']);
            $data['end_time'] = strtotime($data['end_time']);
			$data['integral'] = \intval($data['integral']);
			$content = [];
			foreach(\explode(PHP_EOL,$data['content_string']) as $k => $v){
				$content[]['title'] = $v;
			}
			$data['content'] = \json_encode($content);
            if($data['start_time'] > $data['end_time']){
                $this->error('使用日期填写有误');
            }
			if(\count($data['goods_id']) == 0)
				$this->error('商品必须选择一个');
			
			$data['goods_id'] = $data['goods_id'][0];
			$goods_info = M('goods')->where(['goods_id'=>$data['goods_id']])->find();
			if(!$goods_info)
				$this->error('无此商品');
			
			$data['shop_id'] = $goods_info['shop_id'];
			$data['last_update'] = time();
            if(empty($data['id'])){
            	
            	$row = M('free_prizes')->add($data);
            }else{
            	$row =  M('free_prizes')->where(array('id'=>$data['id']))->save($data);
            }
            if(!$row){
                $this->error('编辑活动失败');
			}	
			if(empty($data['id'])){
				free_prizes_log($row, 0,"管理员新增活动");
			}else{
				free_prizes_log($row, 0,"管理员修改活动");
			}
			
            $this->success('编辑活动成功',U('Admin/Freeprizes/index'));
            exit;
        }
        $cid = I('get.id');
        if($cid){
        	$free_prizes = M('free_prizes')->where(array('id'=>$cid))->find();
			// 处理活动须知
			$content_string = '';
			foreach(\json_decode($free_prizes['content'],true) as $k => $v){
				$content_string .= $v['title'].PHP_EOL;
			}
			$free_prizes['content_string'] = $content_string;
			$freeprizess_goods = M('goods')->where(['goods_id'=>$free_prizes['goods_id']])->select();
			$this->assign('freeprizess_goods', $freeprizess_goods);
        	$this->assign('free_prizes',$free_prizes);
        }else{
        	$def['start_time'] = strtotime("+1 day");
        	$def['end_time'] = strtotime("+1 month");
        	$this->assign('free_prizes',$def);
        }     
        $this->display();
    }
	
	public function search_goods()
	{
		$GoodsLogic = new \Admin\Logic\GoodsLogic;
		$brandList = $GoodsLogic->getSortBrands();
		$this->assign('brandList', $brandList);
		$categoryList = $GoodsLogic->getSortCategory();
		$this->assign('categoryList', $categoryList);
	
		$goods_id = I('goods_id');
		$where = ' is_on_sale = 1 and prom_type=0 and store_count>0 ';//搜索条件
	
		if ($this->shop_info) {
			$where .= " and shop_id=" . $this->shop_info['shop_id'];
		}
	
		if (!empty($goods_id)) {
			$where .= " and goods_id not in ($goods_id) ";
		}
		I('intro') && $where .= " and " . I('intro') . " = 1";
		if (I('cat_id')) {
			$this->assign('cat_id', I('cat_id'));
			$grandson_ids = getCatGrandson(I('cat_id'));
			$where .= " and cat_id in(" . implode(',', $grandson_ids) . ") "; // 初始化搜索条件
		}
		if (I('brand_id')) {
			$this->assign('brand_id', I('brand_id'));
			$where .= " and brand_id = " . I('brand_id');
		}
		if (!empty($_REQUEST['keywords'])) {
			$this->assign('keywords', I('keywords'));
			$where .= " and (goods_name like '%" . I('keywords') . "%' or keywords like '%" . I('keywords') . "%')";
		}
		$count = M('goods')->where($where)->count();
		$Page = new \Think\Page($count, 10);
		$goodsList = M('goods')
			->where($where)
			->order('goods_id DESC')
			->limit($Page->firstRow . ',' . $Page->listRows)
			->fetchSql(0)
			->select();
		$show = $Page->show();//分页显示输出
		$this->assign('page', $show);//赋值分页输出
		$this->assign('goodsList', $goodsList);
		$tpl = I('get.tpl', 'search_goods');
		$this->display($tpl);
	}

    /*
    * 优惠券发放
    */
    public function make_coupon(){
        //获取优惠券ID
        $cid = I('get.id');
        $type = I('get.type');
        //查询是否存在优惠券
        $data = M('coupon')->where(array('id'=>$cid))->find();
        $remain = $data['createnum'] - $data['send_num'];//剩余派发量
    	if($remain<=0) $this->error($data['name'].'已经发放完了');
        if(!$data) $this->error("优惠券类型不存在");
        if($type != 4) $this->error("该优惠券类型不支持发放");
        if(IS_POST){
            $num  = I('post.num');
            if($num>$remain) $this->error($data['name'].'发放量不够了');
            if(!$num > 0) $this->error("发放数量不能小于0");
            $add['cid'] = $cid;
            $add['type'] = $type;
            $add['send_time'] = time();
            for($i=0;$i<$num; $i++){
                do{
                    $code = get_rand_str(8,0,1);//获取随机8位字符串
                    $check_exist = M('coupon_list')->where(array('code'=>$code))->find();
                }while($check_exist);
                $add['code'] = $code;
                M('coupon_list')->add($add);
            }
            M('coupon')->where("id=$cid")->setInc('send_num',$num);
            adminLog("发放".$num.'张'.$data['name']);
            $this->success("发放成功",U('Admin/Coupon/index'));
            exit;
        }
        $this->assign('coupon',$data);
        $this->display();
    }
    
    public function send_coupon(){
    	$cid = I('cid');    	
    	if(IS_POST){
    		$level_id = I('level_id');
    		$user_id = I('user_id');
    		$insert = '';
    		$coupon = M('coupon')->where("id=$cid")->find();
    		if($coupon['createnum']>0){
    			$remain = $coupon['createnum'] - $coupon['send_num'];//剩余派发量
    			if($remain<=0) $this->error($coupon['name'].'已经发放完了');
    		}
    		
    		if(empty($user_id) && $level_id>=0){
    			if($level_id==0){
    				$user = M('users')->where("is_lock=0")->select();
    			}else{
    				$user = M('users')->where("is_lock=0 and level_id=$level_id")->select();
    			}
    			if($user){
    				$able = count($user);//本次发送量
    				if($coupon['createnum']>0 && $remain<$able){
    					$this->error($coupon['name'].'派发量只剩'.$remain.'张');
    				}
    				foreach ($user as $k=>$val){
    					$user_id = $val['user_id'];
    					$time = time();
    					$gap = ($k+1) == $able ? '' : ',';
    					$insert .= "($cid,1,$user_id,$time)$gap";
    				}
    			}
    		}else{
    			$able = count($user_id);//本次发送量
    			if($coupon['createnum']>0 && $remain<$able){
    				$this->error($coupon['name'].'派发量只剩'.$remain.'张');
    			}
    			foreach ($user_id as $k=>$v){
    				$time = time();
    				$gap = ($k+1) == $able ? '' : ',';
    				$insert .= "($cid,1,$v,$time)$gap";
    			}
    		}
			$sql = "insert into __PREFIX__coupon_list (`cid`,`type`,`uid`,`send_time`) VALUES $insert";
			M()->execute($sql);
			M('coupon')->where("id=$cid")->setInc('send_num',$able);
			adminLog("发放".$able.'张'.$coupon['name']);
			$this->success("发放成功");
			exit;
    	}
    	$level = M('user_level')->select();
    	$this->assign('level',$level);
    	$this->assign('cid',$cid);
    	$this->display();
    }
    

    /*
     * 删除活动类型
     */
    public function del_freeprizes(){
        //获取活动ID
        $cid = I('get.id');
        //查询是否存在活动
        $row = M('free_prizes')->where(array('id'=>$cid))->find();
        if($row){
            //删除此类型下的优惠券
            // M('coupon_list')->where(array('cid'=>$cid))->delete();
            // $this->success("删除成功");
        }else{
            $this->error("无此活动");
        }
    }


    /*
     * 优惠券详细查看
     */
    public function coupon_list(){
        //获取优惠券ID
        $cid = I('get.id');
        //查询是否存在优惠券
        $check_coupon = M('coupon')->field('id,type')->where(array('id'=>$cid))->find();
        if(!$check_coupon['id'] > 0)
            $this->error('不存在该类型优惠券');
       
        //查询该优惠券的列表的数量
        $sql = "SELECT count(1) as c FROM __PREFIX__coupon_list  l ".
                "LEFT JOIN __PREFIX__coupon c ON c.id = l.cid ". //联合优惠券表查询名称
                "LEFT JOIN __PREFIX__order o ON o.order_id = l.order_id ".     //联合订单表查询订单编号
                "LEFT JOIN __PREFIX__users u ON u.user_id = l.uid WHERE l.cid = ".$cid;    //联合用户表去查询用户名        
        
        $count = M()->query($sql);
        $count = $count[0]['c'];
    	$Page = new \Think\Page($count,10);
    	$show = $Page->show();
        
        //查询该优惠券的列表
        $sql = "SELECT l.*,c.name,o.order_sn,u.nickname FROM __PREFIX__coupon_list  l ".
                "LEFT JOIN __PREFIX__coupon c ON c.id = l.cid ". //联合优惠券表查询名称
                "LEFT JOIN __PREFIX__order o ON o.order_id = l.order_id ".     //联合订单表查询订单编号
                "LEFT JOIN __PREFIX__users u ON u.user_id = l.uid WHERE l.cid = ".$cid.    //联合用户表去查询用户名
                " limit {$Page->firstRow} , {$Page->listRows}";
        $coupon_list = M()->query($sql);
        $this->assign('coupon_type',C('COUPON_TYPE'));
        $this->assign('type',$check_coupon['type']);       
        $this->assign('lists',$coupon_list);            	
    	$this->assign('page',$show);        
        $this->display();
    }

    /*
     * 选择奖品的优惠券列表
     */
    public function coupon_list_for_prize(){
        
        $Coupon = M('coupon');

        $where = [];

        // 默认选择1天以后到期的
        $where['use_end_time'] = ["gt",time()+86400];

        $type = I('get.type');
        
        if($type)
        {
            $where['type'] = $type;
        } 
        
        $keyword = I('get.keyword');
        
        if($keyword)
        {
            $where['name'] = ["like",'%'.$keyword.'%'];
        } 
       
        $count = $Coupon->where($where)->count();
        $Page = new \Think\Page($count,10);
        $show = $Page->show();
        
        //查询该优惠券的列表
        $coupon_list = $Coupon->where($where)->limit($Page->firstRow,$Page->listRows)->select();

        $this->assign('coupon_type',C('COUPON_TYPE'));
        $this->assign('type',$type);
        $this->assign('keyword',$keyword);
        $this->assign('lists',$coupon_list);                
        $this->assign('page',$show);        
        $this->display();
    }
    
    /*
     * 删除一张优惠券
     */
    public function coupon_list_del(){
        //获取优惠券ID
        $cid = I('get.id');
        if(!$cid)
            $this->error("缺少参数值");
        //查询是否存在优惠券
         $row = M('coupon_list')->where(array('id'=>$cid))->delete();
        if(!$row)
            $this->error('删除失败');
        $this->success('删除成功');
    }
}